package org.knot.mockejb3.annotation;

import java.lang.reflect.Field;

import org.knot.mockejb3.EjbBeanAccess;
import org.knot.mockejb3.annotation.lifeCycle.EJB;
import org.knot.mockejb3.createors.DefaultServiceImpl;
import org.knot.mockejb3.createors.SessionBeanFactory;



/**
 * 针对 EJB注释 的处理
 * @author yuxiaowei
 *
 */
public class EJBAnnotationRuleImpl implements AnnotationRule , EJB {

    public void invoke(RuleParams params) throws Exception{
  
       switch( params.getFalg()){
       case 1:
           if (params.getMethod().getName().startsWith("set") &&  params.getMethod().getParameterTypes().length ==1)
           {
              Class interfaceClazz =  params.getMethod().getParameterTypes()[0];
              Class implClass =  DefaultServiceImpl.getServiceImplClass(interfaceClazz);
              params.setImplClass(implClass);
              params.setInterfaceClass(interfaceClazz);
              
              if (null !=  AnnotationRuleManager.getInstance().getStateLessBeanMap().get(implClass.getClass().getName()))
              {
                  Object sessionBean =  SessionBeanFactory.getInstance().getEJB(interfaceClazz, implClass, params.getKey());
                 
                  params.getMethod().invoke(params.getSessionBean().getBean(), sessionBean);
                  
                  
              }
           }
           else
           {
               throw  new RuntimeException("EJB标签只能配置在属性字段和set方法上面，请检查类；" + params.getSessionBean().getClass().getName());
           }
           break;
           
       case 2:
           Field field =  params.getField();
           Class interfaceClazz = field.getType();
           Class implClass = interfaceClazz;
           if (field.getGenericType().toString().startsWith("interface"))
           {
               implClass =  DefaultServiceImpl.getServiceImplClass(interfaceClazz);
           }
           params.setImplClass(implClass);
           params.setInterfaceClass(interfaceClazz);
           Object sessionBean =  SessionBeanFactory.getInstance().getEJB(interfaceClazz, implClass, params.getKey());
           field.setAccessible(true); 
           field.set(params.getSessionBean().getBean(), sessionBean);
           break;
           
        default:
               throw  new RuntimeException("EJB标签只能配置在属性字段和set方法上面，请检查类；" + params.getSessionBean().getClass().getName());
               
       }
       
    }

}
